# import logging as logging
# import global_config
from minio import Minio
from minio.error import *
import io
import pickle
import os
from loguru import logger


# 判断桶是否存在
class Minio_Utils():
    # 登陆minio客户端

    # minioClient = Minio('172.26.36.188:9000',
    #                     access_key='Admin',
    #                     secret_key='Admin123',
    #                     secure=False)

    def __init__(self,global_config) -> None:
        self.minioClient = Minio(global_config.MINIO_URL,
                    access_key=global_config.MINIO_ACCESS_KEY,
                    secret_key=global_config.MINIO_SECRET_KEY,
                    secure=False)

    # 判断桶是否存在
    def check_bucket_exists(self, bucket_name):

        """
          判断桶是否存在

        Args:
            bucket_name (_type_): _description_
        """
        try:
            if (self.minioClient.bucket_exists(bucket_name)):
                pass
                logger.info("Minio_Utils --> bucket桶存在")
            else:
                self.minioClient.make_bucket(bucket_name)
                logger.info("Minio_Utils --> 创建新bucket桶：{}",bucket_name)
        except InvalidResponseError as err:
            logger.error(err)

    def minio_upload_file(self, bucket_name, object_name, file_path):
        """
        上传文件到minion 的 bucket中

        Args:
            bucket_name (_type_): _description_
            object_name (_type_): _description_
            file_path (_type_): _description_

        Returns:
            _type_: _description_
        """
        self.check_bucket_exists(bucket_name=bucket_name)
        try:
            # logger.info("start upload file")
            self.minioClient.fput_object(
                bucket_name=bucket_name,
                object_name=object_name,
                file_path=file_path
            )
            logger.info("Minio_Utils --> minio file successfully uploaded")
            return True
        except FileNotFoundError as err:
            logger.error('Minio_Utils --> upload_failed: ' + str(err))
            return False
        except S3Error as err:
            logger.error("Minio_Utils --> upload_failed:"+str( err))
            return False

    # def get_bucket_file(self,bucket_name,object_name):
    #     try:
    #         # self.minioClient.get_object()
    #         pass

    #     except ResponseError as err:
    #         logger.info(err)

    def check_file_exists(self, bucket_name, file_name):
        """
        检查文件是否在bucket 中

        Args:
            bucket_name (_type_): _description_
            file_name (_type_): _description_

        Returns:
            _type_: _description_
        """
        try:
            data = self.minioClient.stat_object(bucket_name, file_name)
            # print(data.bucket_name)
            # print(data.object_name)
            # print(data.last_modified)
            # print(data.etag)
            # print(data.size)
            # print(data.metadata)
            # print(data.content_type)
            if (data is not None):
                return True
            else:
                return False
        except S3Error as e:
            return None

    def file_stat_object(self, bucket_name, file):
        """      
        获取文件元数据,查询状态

        Args:
            bucket_name (_type_): _description_
            file (_type_): _description_

        Returns:
            Bool: _description_
        """
        try:
            data = self.minioClient.stat_object(bucket_name, file)
            # print(data.bucket_name)
            # print(data.object_name)
            # print(data.last_modified)
            # print(data.etag)
            # print(data.size)
            # print(data.metadata)
            # print(data.content_type)
            if (data is not None):
                return True
        except S3Error as e:
            return None
            # print("[error]:", e)
    def upload_file_use_pkl(self, bucket_name,file_data, file_name):
        # 判断桶是否存在
        # check_bucket = self.minioClient.bucket_exists(bucket_name)
        self.check_bucket_exists(bucket_name=bucket_name)
        try:
            file_data = pickle.dumps(file_data)
            file = io.BytesIO(file_data)
            self.minioClient.put_object(bucket_name,file_name,file,len(file_data),content_type='application/pkl')
            logger.info("Minio_Utils --> successfully uploaded")
        except S3Error as err:
            logger.error("Minio_Utils --> upload_failed:", err)
    def download_file_from_minio(self,buckert_name,file_name,save_file_path):
        # sava_file_path = os.path.join(os.path.abspath(os.path.dirname(__name__)), 'minio_files')
        dir_list = os.listdir(save_file_path)

        file_path = os.path.join(save_file_path, *(file_name.split('/')))
        logger.info(file_path)
        if file_name in dir_list:
            logger.info('Minio_Utils --> {0}在本地已经存在'.format(file_name))
        else:
            logger.info('Minio_Utils --> 本地不存在文件,去minio中下载{0}'.format(file_name))
            self.minioClient.fget_object(buckert_name,file_name,file_path)
            logger.info('Minio_Utils --> minio中下载{0},下载完成'.format(file_name))



if __name__ == '__main__':

    from applications.configs import global_config

# # ########################2022-04-01######################
    # print(123)
    # import pandas as pd
    
    # data = {'column1': [1, 1, 1, ], 'column2': [2, 2, 2], 'column3': [3, 3, 3]}
    # df = pd.DataFrame(data)
    # print(df)
    # print(type(df))
    minio_utils=Minio_Utils(global_config['Dev'])
    # process_id=20220602
    # require='tracing'
    # key = str(process_id) + "-" + require + ".pkl"
    # save_file_path=os.path.join(os.path.abspath(os.path.dirname(__name__)), '..')
    # logger.info(save_file_path)
    # minio_utils.download_file_from_minio(key,save_file_path)
    print('success')
    # # minio_utils=Minio_Utils(Dev)
    # minio_utils.upload_file_use_pkl("mly-test",data,"test123.pkl")
    # print(11111111111)
    # # pkl_data = minio_utils.minioClient.get_object(bucket_name, key1+".pkl")
    # # 获取文件中的数据
    # # tracing_res = pickle.load(pkl_data)